package io.vertx.kue.queue

import io.vertx.kue.service.*
import io.vertx.kue.util.RedisHelper
import io.vertx.core.AbstractVerticle
import io.vertx.core.Future
import io.vertx.core.json.JsonObject
import io.vertx.core.logging.Logger
import io.vertx.core.logging.LoggerFactory
//import io.vertx.serviceproxy.ProxyHelper
import io.vertx.serviceproxy.ServiceBinder


/**
 * Vert.x Blueprint - Job Queue
 * Kue Verticle
 *
 * @author Eric Zhao
 */
class KueVerticle : AbstractVerticle() {

    private var config: JsonObject? = null
    private var jobService: JobService? = null

    @Throws(Exception::class)
    override fun start(future: Future<Void>) {
        this.config = config()
        this.jobService = JobService_create(vertx, config!!)
        // create redis client
        val redisClient = RedisHelper.client(vertx, config!!)
        redisClient.ping { // test connection
            pr ->
            if (pr.succeeded()) {
                logger.info("Kue Verticle is running...")

                // register job service
                //ProxyHelper.registerService(JobService::class.java, vertx, jobService, EB_JOB_SERVICE_ADDRESS)
                ServiceBinder(vertx)
                        .setAddress(EB_JOB_SERVICE_ADDRESS)
                        .register(JobService::class.java, jobService)

                future.complete()
            } else {
                logger.error("oops!", pr.cause())
                future.fail(pr.cause())
            }
        }
    }

    companion object {

        private val logger = LoggerFactory.getLogger(Job::class.java)

        val EB_JOB_SERVICE_ADDRESS = "vertx.kue.service.job.internal"
    }

}
